package com.eurasia.firstapp.services;

import com.eurasia.firstapp.entities.User;
import com.eurasia.firstapp.exceptions.BusinessException;
import com.eurasia.firstapp.repositories.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.Optional;

@Service
public class UserService {
    @Autowired
    private UserRepository userRepository;

    public User register(String username, String password) throws BusinessException {
        if (isAlreadyExist(username)) {
            throw new BusinessException("username is already exist");
        }
        return addUser(username, password);
    }

    private User addUser(String username, String password) {
        User user = new User(username, password);
        return userRepository.save(user);
    }

    private boolean isAlreadyExist(String username) {
        User user = userRepository.findByUsername(username);
        return Objects.nonNull(user);
    }

    public User login(String username, String password) throws BusinessException {
        User user = userRepository.findByUsernameAndPassword(username, password);
        if (Objects.isNull(user)) {
            throw new BusinessException("username or password is wrong");
        }
        return user;
    }

    public User findUserById(Long id) throws BusinessException {
        Optional<User> userOpt = userRepository.findById(id);
        if (userOpt.isPresent()) {
            return userOpt.get();
        }
        throw new BusinessException("user is not exist");
    }

    public void deleteUserById(Long id) throws BusinessException {
        User user = findUserById(id);

        userRepository.delete(user);
    }

    public void updateUser(Long id, String password) throws BusinessException {
        User user = findUserById(id);
        user.setPassword(password);

        userRepository.save(user);
    }

    public List<User> findUsers() {
        return userRepository.findAll();
    }
}
